﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using DAL;
using System.Security.Cryptography;
using System.Text;

/// <summary>
/// Summary description for Utilities
/// Create by Phinv 20130315
/// </summary>
public class Utilities
{
    public static bool CheckQuyenTruyCap(string UserID, string ChucNang)
    {
        if (ChucNang == null) ChucNang = "";
        if (UserID == null) UserID = "";
        int int_UserID = 0;
        int int_ChucNang = 0;
        int.TryParse(UserID.Trim(), out int_UserID);
        int.TryParse(ChucNang.Trim(), out int_ChucNang);
        SqlConnection sqlConnec = ConnectData.getConnection();
        DAQuyen objQuyen = new DAQuyen(sqlConnec);
        if (int_ChucNang == -1) return true;
        return objQuyen.CheckQuyen(int_UserID, int_ChucNang);
    }
    public static string LoadTruong(string truongId)
    {
        try
        {
            int idTruong = 0;
            int.TryParse(truongId, out idTruong);
            if (idTruong == 0) return "---";
            else
            {
                SqlConnection sqlConnec = ConnectData.getConnection();
                DATruong objQuyen = new DATruong(sqlConnec);
                return objQuyen.loadTruongID(idTruong)["Ten"].ToString();
            }
        }
        catch (Exception)
        {
            return "---";
        }

    }
    /// <summary>
    /// string to datetime
    /// </summary>
    /// <param name="ip_str_datetime">dạng: 20140122202927</param>
    /// <returns></returns>
    public static DateTime string_2_datetime(string ip_str_datetime)
    {
        string v_str_year = ip_str_datetime.Substring(0, 4);
        string v_str_month = ip_str_datetime.Substring(4, 2);
        string v_str_day = ip_str_datetime.Substring(6, 2);
        string v_str_hour = ip_str_datetime.Substring(8, 2);
        string v_str_minute = ip_str_datetime.Substring(10, 2);
        string v_str_second = ip_str_datetime.Substring(12, 2);
        DateTime dat_out_datetime = new DateTime(Convert.ToInt32(v_str_year)
                                            , Convert.ToInt32(v_str_month)
                                            , Convert.ToInt32(v_str_day)
                                            , Convert.ToInt32(v_str_hour)
                                            , Convert.ToInt32(v_str_minute)
                                            , Convert.ToInt32(v_str_second));
        return dat_out_datetime;
    }
    public static string GetFullNameTVTS(string nguoidungId)
    {
        try
        {
            int idNguoiDung = 0;
            int.TryParse(nguoidungId, out idNguoiDung);
            if (idNguoiDung == 0) return "---";
            else
            {
                SqlConnection sqlConnec = ConnectData.getConnection();
                DANguoidung objQuyen = new DANguoidung(sqlConnec);
                return objQuyen.loadNguoidungID(idNguoiDung)["HoTen"].ToString();
            }
        }
        catch (Exception)
        {
            return "---";
        }

    }
    public static bool ValidatePhoneMask(string strphone)
    {
        System.Text.RegularExpressions.Regex regexObj =
            new System.Text.RegularExpressions.Regex(@"^([0-9]{3,5})?[ ]?([0-9]{3})[ ]?([0-9]{3})$");
        return regexObj.IsMatch(strphone);
    }
    public static string chuan_hoa_so_dien_thoai(string ip_str_sdt)
    {

        try
        {
            string[] v_array = { ".", ",", " ", "-" };
            // Nếu có các ký tự đặc biệt, loại bỏ
            for (int v_i = 0; v_i < v_array.Length; v_i++)
            {
                while (ip_str_sdt.Contains(v_array[v_i]))
                {
                    ip_str_sdt = ip_str_sdt.Replace(v_array[v_i], "");
                }
            }
            while (ip_str_sdt.Substring(0, 1) == "0")
            {
                ip_str_sdt = ip_str_sdt.Substring(1, ip_str_sdt.Length - 1);
            }
            return ip_str_sdt.Substring(0, ip_str_sdt.Length - 6) + " " + ip_str_sdt.Substring(ip_str_sdt.Length - 6, 3) + " " + ip_str_sdt.Substring(ip_str_sdt.Length - 3, 3);
        }
        catch (Exception)
        {
            return "";
        }

    }
    public static string mapping_levelId_ten_level(int ip_levelid)
    {
        string v_str_level = "";
        switch (ip_levelid)
        {
            case 1:
                v_str_level = "Level 1";
                break;
            case 2:
                v_str_level = "Level 2";
                break;
            case 3:
                v_str_level = "Level 3";
                break;
            case 4:
                v_str_level = "Level 4";
                break;
            case 5:
                v_str_level = "Level 5A";
                break;
            case 6:
                v_str_level = "Level 5B";
                break;
            case 7:
                v_str_level = "Level 6";
                break;
            case 8:
                v_str_level = "Level 7";
                break;
            case 9:
                v_str_level = "Level 8";
                break;
            case 10:
                v_str_level = "Level 9";
                break;
        }
        return v_str_level;
    }
    public static string dien_thoai_Output(string ip_str_sdt)
    {

        try
        {
            string[] v_array = { ".", ",", " ", "-" };
            // Nếu có các ký tự đặc biệt, loại bỏ
            for (int v_i = 0; v_i < v_array.Length; v_i++)
            {
                while (ip_str_sdt.Contains(v_array[v_i]))
                {
                    ip_str_sdt = ip_str_sdt.Replace(v_array[v_i], "");
                }
            }

            return ip_str_sdt;
        }
        catch (Exception)
        {
            return "";
        }

    }
    public static void WriteToLog(Exception i_exeption)
    {
        string v_str_path;
        v_str_path = AppDomain.CurrentDomain.BaseDirectory + "Logs/";
        write_string_2_log_file(i_exeption.Message + Environment.NewLine + i_exeption.Source, v_str_path);
    }
    public static void WriteToLog(string ip_str_content_log)
    {
        string v_str_path;
        v_str_path = AppDomain.CurrentDomain.BaseDirectory + "Logs/";
        write_string_2_log_file(ip_str_content_log + Environment.NewLine, v_str_path);
    }
    private static void write_string_2_log_file(string i_str_error, string i_str_path)
    {
        System.IO.StreamWriter m_stream_writer;
        try
        {
            string v_str_filename;
            v_str_filename = i_str_path + DateTime.Now.ToString("yyyyMMddHHmm") + ".log";
            if (System.IO.File.Exists(v_str_filename))
                m_stream_writer = System.IO.File.AppendText(v_str_filename);
            else m_stream_writer = System.IO.File.CreateText(v_str_filename);
            m_stream_writer.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss ") + i_str_error);
            m_stream_writer.Close();
        }
        finally
        {
        }
    }

    public static string Encrypt(string toEncrypt, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
        string key = "a123090";
        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);
        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = tdes.CreateEncryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        tdes.Clear();
        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }

    /// <summary>
    /// DeCrypt a string using dual encryption method. Return a DeCrypted clear string
    /// </summary>
    /// <param name="cipherString">encrypted string</param>
    /// <param name="useHashing">Did you use hashing to encrypt this data? pass true is yes</param>
    /// <returns></returns>
    public static string Decrypt(string cipherString, bool useHashing)
    {
        byte[] keyArray;
        byte[] toEncryptArray = Convert.FromBase64String(cipherString);
        string key = "a123090";

        if (useHashing)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            hashmd5.Clear();
        }
        else
            keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        tdes.Key = keyArray;
        tdes.Mode = CipherMode.ECB;
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        tdes.Clear();
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
}